package org.alis.smallcc.designpatterns.behavior.iterator;

import java.util.Arrays;
import java.util.function.Consumer;

/**
 * 数组集合
 * 
 * @author luochuan
 */
public class ArrayAggregate<T> implements Aggregate<T>{

	private T[] array;
	
	private int size;
	
	public ArrayAggregate() {
		this.size = 0;
		this.array=(T[])new Object[this.size];
	}
	
	
	@Override
	public int add(T t) {
		this.array = Arrays.copyOf(array, ++size);
		this.array[size-1]=t;
		return size-1;
	}

	@Override
	public int remove(T t) {
		int index=0;
		T[] tempArray = (T[]) new Object[size-1];
		boolean flag = Arrays.stream(this.array).anyMatch(obj->obj.equals(t));
		if(!flag) {
			return -1;
		}
		int j=0;
		for(int i=0;i<this.size;i++) {
			if(!this.array[i].equals(t)) {
				tempArray[j++]=this.array[i];
			}else{
				index=i;
			}
		}
		this.array=tempArray;
		return index;
	}

	@Override
	public Iterator<T> iterator() {
		return new AggregateIterator<>(this);
	}
	@Override
	public void forEach(Consumer<T> consumer) {
		for(T t : array) {
			consumer.accept(t);
		}
	}

	@Override
	public int size() {
		return this.size;
	}

	@Override
	public T get(int cursor) {
		if(cursor <0 ||this.size < cursor) {
			throw new IllegalStateException(String.format("超出数组长度，数组长度%d,获取长度%d",this.size,cursor));
		}
		return array[cursor];
	}


	@Override
	public T remove(int cursor) {
		if(cursor <0 ||this.size < cursor) {
			throw new IllegalStateException(String.format("超出数组长度，数组长度%d,获取长度%d",this.size,cursor));
		}
		T[] temp = (T[])new Object[this.size-1];
		T t = null;
		int j=0;
		for(int i=0;i<this.size;i++) {
			if(i==cursor) {
				t=this.array[i];
			}else {
				temp[j++]=this.array[i];
			}
		}
		size++;
		this.array = temp;
		return t;
		
		
		
		
	}

}
